package com.wz.jiangsu.main.td;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class TDengineInsertExample {

    public static void main(String[] args) throws Exception{
        // TDengine 服务器地址和端口
        String host = "127.0.0.1";
        int port = 6030;
        // 数据库名
        String dbName = "testdb";
        // 用户名和密码（如果设置了）
        String user = "root";
        String password = "taosdata";

        // JDBC URL
        String jdbcUrl = "jdbc:TAOS://" + host + ":" + port + "/" + dbName + "?user=root&password=taosdata";

        // SQL 插入语句
        String sql = "INSERT INTO sensor_data (ts, device_id, cpu_1m_avg, free_mem, used_mem, net_rssi, net_loss, battery, temperature, humidity, pressure, CO, NO2, PM10) " +
                "TAGS (location_id, dev_type, firmware_version, customer_id) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) TAGS (?, ?, ?, ?)";

        try (
            // 加载 JDBC 驱动
//            Class.forName("com.taosdata.jdbc.TSDBDriver");
            // 建立连接
            Connection conn = DriverManager.getConnection(jdbcUrl);
            // 创建 PreparedStatement
            PreparedStatement pstmt = conn.prepareStatement(sql)
        ) {
            // 设置参数值
            pstmt.setTimestamp(1, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
            pstmt.setBytes(2, java.util.UUID.randomUUID().toString().getBytes());
            pstmt.setFloat(3, 0.5f);
            pstmt.setFloat(4, 500.0f);
            pstmt.setFloat(5, 1024.0f);
            pstmt.setFloat(6, -65.0f);
            pstmt.setFloat(7, 0.01f);
            pstmt.setFloat(8, 80.0f);
            pstmt.setFloat(9, 25.0f);
            pstmt.setFloat(10, 50.0f);
            pstmt.setFloat(11, 1013.25f);
            pstmt.setFloat(12, 0.0f);
            pstmt.setFloat(13, 0.0f);
            pstmt.setFloat(14, 10.0f);

            // 执行插入
            int affectedRows = pstmt.executeUpdate();
            System.out.println("Inserted " + affectedRows + " row(s).");
        } catch (Exception  e) {
            e.printStackTrace();
        }
    }
}
